import { ConfigService } from '@nestjs/config';
import { Controller, Post, UploadedFile, UseInterceptors, HttpException, HttpStatus } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import * as fs from 'fs';
import { v4 as uuidv4 } from 'uuid';
import  dayjs from 'dayjs';
import { NotAuthorized } from 'src/decorator/roles.decorator';

export type File = {
    fieldname: string;
    originalname: string;
    encoding: string;
    mimetype: string;
    buffer: Buffer;
    size: number;
}

@Controller('file')
export class FileUploadController {
    constructor(private readonly configServ: ConfigService) { }

    @NotAuthorized()
    @Post('upload')
    @UseInterceptors(FileInterceptor('file'))
    upload(@UploadedFile() file: File) {

        if (!file) {
            throw new HttpException('请选择上传文件', HttpStatus.BAD_REQUEST);
        }
        let fileName = uuidv4();
        if (/(\.\w+)/.test(file.originalname)) {
            fileName += RegExp.$1;
        } else {
            fileName += file.originalname;
        }
        let fileType: string;
        let date = dayjs().format('YYYY-MM-DD');


        if (file.mimetype.indexOf('image') !== -1) {
            fileType = 'image';
        } else if (file.mimetype.indexOf('audio') !== -1) {
            fileType = 'audio';
        } else if (file.mimetype.indexOf('video') !== -1) {
            fileType = 'video';
        } else if (file.mimetype.indexOf('pdf') !== -1) {
            fileType = 'pdf';
        } else {
            fileType = 'other';
        }


        const path = `${this.configServ.get('ASSETS').root}/${fileType}/${date}/`;
        const readPath = `${this.configServ.get('ASSETS').prefix}/${fileType}/${date}/`;
        try {
            /**
             * 先创建文件夹，再写入文件，防止写入错误
             */
            fs.mkdirSync(path, {
                recursive: true, // 循环进行创建
            }); // 创建文件夹
            fs.writeFileSync(path + fileName, file.buffer);
            var url = readPath + fileName;
        } catch (error) {
            throw error;
        }

        if (!url) {
            throw new HttpException("图片上传错误", HttpStatus.INTERNAL_SERVER_ERROR)
        }
        // 拼接完整访问路径
        url = `${this.configServ.get('host')}:${this.configServ.get('port')}` + url;
        return { url };
    }
}
 